<template>
  <div class="app-container">
    <el-row :gutter="20" span="24">
      <el-col :md="5" :sm="24" :xs="24">
        <div style="margin-bottom: 15px; display: flex; -webkit-box-align: center; align-items: center">
          <el-input v-model="filterText" size="small" placeholder="输入部门进行过滤"></el-input>
        </div>
        <el-tree
          ref="tree"
          :data="deptTrees.trees"
          node-key="id"
          :props="deptTrees.props"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          :highlight-current="true"
          @node-click="deptNodeClick"
        >
        </el-tree>
      </el-col>
      <el-col :md="19" :sm="24" :xs="24">
        <div class="filter-container">
          <el-input v-model="listQuery.username" placeholder="输入用户名" size="small" class="input-with-select" style="width: 200px;" @keyup.enter.native="getUsers">
            <el-button slot="append" icon="el-icon-search" @click="getUsers"></el-button>
          </el-input>
          <el-button style="margin-left: 10px;" icon="el-icon-delete" size="small" @click="resetQuery">
            清空
          </el-button>
          <el-button size="small" style="display: block; margin: 10px 0" type="primary" icon="el-icon-edit" @click="handleCreate">
            添加
          </el-button>
        </div>
        <el-table
          v-loading="listLoading"
          :data="userList"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
        >
          <el-table-column align="center" label="编号" width="95">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="用户名" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.username }}</span>
            </template>
          </el-table-column>
          <el-table-column label="手机号" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.mobile }}</span>
            </template>
          </el-table-column>
          <el-table-column label="邮箱地址" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.email }}</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.deptName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="角色" align="center">
            <template slot-scope="scope">
              <el-tag v-for="item in scope.row.roleList" :key="item.id">{{ item.roleName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.locked" type="danger">锁定</el-tag>
              <el-tag v-else>有效</el-tag>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
            <template slot-scope="{row}">
              <el-button size="mini" @click="handleUpdate(row)">
                编辑
              </el-button>
              <el-button size="mini" type="danger" @click="deleted(row.id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" style="text-align: right" :total="total" :page.sync="listQuery.current" :limit.sync="listQuery.size" @pagination="getUsers" />

      </el-col>
    </el-row>

    <!-- 添加/编辑 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="temp.username" size="small" :disabled="updateDisable"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="temp.password" size="small" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" size="small" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="temp.mobile" size="small" />
        </el-form-item>
        <el-form-item label="所属部门" prop="dept">
          <treeselect v-model="temp.deptId" :options="deptTrees.trees" :normalizer="normalizer" placeholder="请选择部门" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="temp.roleIds" multiple placeholder="请选择角色">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="locked">
          <el-radio-group v-model="temp.locked" size="mini">
            <el-radio :label="false" border>有效</el-radio>
            <el-radio :label="true" border>锁定</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create'? created() : updated() ">
          确认
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  // import the component
  import Treeselect from '@riophae/vue-treeselect'
  // import the styles
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import Pagination from '@/components/Pagination'
  import { getUserList, saveUser, updateUser, deleteUser } from '@/api/user'
  import { getDeptTree } from '@/api/dept'
  import { getRoles } from '@/api/role'
  import { validEmail, validMobile } from '@/utils/validate'

  // 邮箱验证
  const validateEmail = (rule, value, callback) => !validEmail(value) ? callback(new Error('邮箱格式有误')) : callback()

  // 手机号验证
  const validateMobile = (rule, value, callback) => !validMobile(value) ? callback(new Error('手机号格式有误')) : callback()

  export default {
    name: 'User',
    components: { Pagination, Treeselect },
    data() {
      return {
        updateDisable: false,
        filterText: '',
        deptId: undefined,
        roleList: [],
        deptTrees: {
          trees: [],
          props: {
            children: 'children',
            label: 'name'
          }
        },
        calendarTypeOptions: [
          { key: 'CN', display_name: 'China' },
          { key: 'US', display_name: 'USA' },
          { key: 'JP', display_name: 'Japan' },
          { key: 'EU', display_name: 'Eurozone' }
        ],
        userList: [],
        listQuery: {
          current: 1,
          size: 10,
          deptId: '',
          username: ''
        },
        total: 0,
        statusOptions: ['published', 'draft', 'deleted'],
        listLoading: true,
        dialogStatus: '',
        dialogFormVisible: false,
        temp: {
          id: undefined,
          username: '',
          password: '',
          email: '',
          mobile: '',
          roleIds: [],
          deptId: '',
          locked: false
        },
        textMap: {
          update: '编辑用户',
          create: '添加用户'
        },
        downloadLoading: false,
        rules: {
          username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
          // password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
          email: [{ required: false, trigger: 'blur', validator: validateEmail }],
          mobile: [{ required: false, trigger: 'blur', validator: validateMobile }],
          dept: [{ required: true, message: '请选择部门', trigger: 'blur' }],
          role: [{ required: true, message: '请选择角色', trigger: 'blur' }]
        }
      }
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val)
      }
    },
    created() {
      this.deptTree()
      this.getUsers()
    },
    methods: {
      resetQuery() {
        this.listQuery = {
            current: 1,
            size: 10,
            deptId: '',
            username: ''
        }
        this.getUsers()
      },
      resetListQuery(size) {
        const pages = Math.ceil((this.total - size) / this.listQuery.size)
        const current = this.listQuery.current > pages ? pages : this.listQuery.current
        this.listQuery.current = current < 1 ? 1 : current
      },
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      },
      deptNodeClick() {
        this.listQuery.deptId = this.$refs.tree.getCurrentKey()
        this.getUsers()
      },
      getRoleList() {
        getRoles().then(({ data }) => {
          this.roleList = data
        })
      },
      getUsers() {
        this.listLoading = true
        getUserList(this.listQuery).then(({ data }) => {
          this.userList = data.records
          this.total = data.total
          this.listLoading = false
        }).catch(error => {
          console.log(error)
          this.$message.error(error)
        })
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          username: '',
          password: '',
          email: '',
          mobile: '',
          roleIds: [],
          deptId: '',
          locked: false
        }
      },
      handleCreate() {
        this.resetTemp()
        this.getRoleList()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.updateDisable = false
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleUpdate(row) {
        this.deptTree()
        this.getRoleList()
        this.temp = Object.assign({}, row) // copy obj
        this.temp.roleIds = this.temp.roleList.map((item) => {
          return item.id
        })
        this.temp.password = undefined
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.updateDisable = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      created() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            saveUser(this.temp).then(({ data }) => {
              this.dialogFormVisible = false
              this.getUsers()
              this.$notify({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
              this.getUsers()
              this.dialogFormVisible = false
            }).catch(() => {
              this.$notify({
                title: '失败',
                message: '添加失败',
                type: 'error',
                duration: 2000
              })
            })
          }
        })
      },
      updated() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            updateUser(this.temp).then(({ data }) => {
              this.dialogFormVisible = false
              this.getUsers()
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getUsers()
              this.dialogFormVisible = false
            }).catch(() => {
              this.$notify({
                title: '失败',
                message: '更新失败',
                type: 'error',
                duration: 2000
              })
            })
          }
        })
      },
      deleted(id) {
        this.$confirm('您确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteUser(id).then(() => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            this.resetListQuery(1)
            this.getUsers()
          }).catch(() => {
            this.$notify.error({
              title: '错误',
              message: '删除失败'
            })
          })
        })
      },
      deptTree() {
        getDeptTree().then(({ data }) => {
          this.deptTrees.trees = data
        }).catch(error => {
          console.log(error)
        })
      },
      filterNode(value, data, node) {
        if (!value) {
          return true
        }
        const _array = []
        this.getReturnNode(node, _array, value)
        let result = false
        _array.forEach(item => {
          result = result || item
        })
        return result
      },
      getReturnNode(node, _array, value) {
        const isPass = node.data && node.data.name && node.data.name.indexOf(value) !== -1
        isPass ? _array.push(isPass) : ''
        this.index++
        console.log(this.index)
        if (!isPass && node.level !== 1 && node.parent) {
          this.getReturnNode(node.parent, _array, value)
        }
      }
    }
  }
</script>

<style type="scss">
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
  .el-input-group__append, .el-input-group__prepend {
    padding: 0 10px;
  }
</style>

<style scoped type="scss">
</style>
